<template>
  <div class="m-pageView">
    <div class="m-searchPanel">
      <div class="layout-1"><span class="leftLine"></span>查询条件</div>
      <div class="layout-2">
        <el-form :model="searchForm" :inline="true">
          <el-row :gutter="30">
                <el-col :span="6">
              <el-form-item class="input-with-select">
                <el-input placeholder=" " v-model.trim="searchForm.inputFH" clearable>
                  <el-select v-model="searchForm.typeinputFH" slot="prepend"
                             class="selectInputType">
                    <el-option label="手机号" value="phone"></el-option>
                    <el-option label="姓名" value="realName"></el-option>
                  </el-select>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="" class="select-timepick">
                <el-select v-model="searchForm.typetimeFH" placeholder="请选择">
                  <el-option label="创建时间" value="create"></el-option>
                  <el-option label="分配时间" value="assign"></el-option>
                </el-select>
                <el-date-picker
                  v-model="searchForm.timeFH"
                  type="datetimerange"
                  :unlink-panels="true"
                  :default-time="['00:00:00','23:59:59']"
                  format="yyyy-MM-dd HH:mm:ss"
                  :time-arrow-control="true"
                  :picker-options="pickerOptions"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="7" class="searchBtns">
              <el-button type="text" @click="showMoreSearchChoise =!showMoreSearchChoise">
                <span>更多条件</span>
                <i :class="{
                  'el-icon-arrow-down':!showMoreSearchChoise,
                  'el-icon-arrow-up':showMoreSearchChoise,
                  }"></i>
              </el-button>
              <el-button type="primary" icon="el-icon-search" @click="search" :loading="dataListLoading">查询</el-button>
              <el-button type="primary" plain icon="el-icon-refresh" @click="reset">重置</el-button>
            </el-col>
          </el-row>
          <el-collapse-transition>
            <el-row :gutter="30" v-if="showMoreSearchChoise">
              <el-col :span="6">
                <el-form-item label="项目">
                  <el-select
                    v-model="searchForm.projects"
                    multiple
                    filterable
                    placeholder="请选择-可输入搜索">
                    <el-option label="N/A" value="0"></el-option>
                    <el-option label="RLA" value="1"></el-option>
                    <el-option label="RLP" value="2"></el-option>
                    <el-option label="RLR" value="4"></el-option>
                    <el-option label="DMA" value="8"></el-option>
                    <el-option label="LBM" value="16"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="LEAD状态">
                  <el-select clearable v-model="searchForm.hstatus" multiple placeholder="请选择">
                    <el-option label="新建" value="1"></el-option>
                    <el-option label="已转化" value="3"></el-option>
                    <el-option label="无效" value="4"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="分配状态">
                  <el-select clearable v-model="searchForm.astatus" placeholder="请选择" clearable>
                    <el-option label="待分配" value="1"></el-option>
                    <el-option label="已分配" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="标记">
                  <el-select
                    v-model="searchForm.labels"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    :remote-method="remoteMarkMethod"
                    placeholder="请输入关键词"
                  >
                    <el-option
                      v-for="item in markabels"
                      :label="item.lname"
                      :key="item.lid"
                      :value="item.lid">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="创建人">
                  <el-select
                    v-model="searchForm.createUser"
                    clearable
                    filterable
                    remote
                    reserve-keyword
                    :remote-method="remoteUserMethod"
                    placeholder="请输入关键字"
                  >
                    <el-option
                      v-for="item in userList"
                      :label="item._id"
                      :key="item._id"
                      :value="item._id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="分配给">
                  <el-select
                    v-model="searchForm.assigner"
                    clearable
                    filterable
                    remote
                    reserve-keyword
                    :remote-method="remoteUserMethod"
                    placeholder="请输入关键字"
                  >
                    <el-option
                      v-for="item in userList"
                      :label="item._id"
                      :key="item._id"
                      :value="item._id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-transition>
        </el-form>
      </div>
    </div>
    <div class="m-dataLayout">
      <div class="m-searchListPanel">
        <div class="layout-1"><span class="leftLine"></span>信息列表</div>
        <div class="layout-2">
          <el-button type="text" icon="el-icon-plus" @click="showAddLeadData = true" v-if="buttonAuthority.lead && buttonAuthority.lead.cs_create">新建</el-button>
          <el-button type="text" icon="el-icon-upload" @click="uploadDatas.show=true" v-if="buttonAuthority.lead && buttonAuthority.lead.upload">上传</el-button>
          <a :href="downLoadHref" download v-if="buttonAuthority.lead && buttonAuthority.lead.excel"><el-button type="text" icon="el-icon-download">导出</el-button></a>
        </div>
      </div>
      <div class="m-dataList">
        <el-table
          :data="dataList"
          style="width: 100%"
          max-height="600"
          v-loading="dataListLoading"
          element-loading-text="loading..."
          ref="dataList"
          @sort-change="tableSortBy"
        >
          <el-table-column
            :render-header="tableRenderHeader"
            width="50">
            <template slot-scope="scope">
              <i @click="activeFocus(scope.row)" :class="{
                  'el-icon-star-off':scope.row.focus == '1',
                  'el-icon-star-on':scope.row.focus == '2'
                }"></i>
            </template>
          </el-table-column>
          <el-table-column
            prop="project"
            min-width="120"
            label="项目">
            <template slot-scope="scope">
              <Comp-project-icons :project="scope.row.project"></Comp-project-icons>
            </template>
          </el-table-column>
          <el-table-column
            prop="realName"
            label="姓名"
            width="120">
          </el-table-column>
          <el-table-column
            prop="phone"
            label="手机号"
            width="120">
            <template slot-scope="scope">
              <router-link :to="{name:'LeadDetailsLeade',params:{id:scope.row.id+'_'+scope.row.phone}}">
                {{scope.row.phone}}
              </router-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="otherPhone"
            label="其他手机号码"
            width="150">
          </el-table-column>
          <el-table-column
            prop="hstatus"
            label="LEAD状态"
            width="100">
            <template slot-scope="scope">
              <span>{{scope.row.hstatus | hstatusLeadToString}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="astatus"
            label="分配状态"
            width="80">
            <template slot-scope="scope">
              <span>{{scope.row.astatus | astatusToString}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="assigner"
            label="分配给"
            width="150">
          </el-table-column>
          <el-table-column
            prop="assignTimeStr"
            sortable="custom"
            label="分配时间"
            width="160">
          </el-table-column>
          <el-table-column
            prop="createUser"
            label="创建人"
            width="100">
          </el-table-column>
          <el-table-column
            prop="createTimeStr"
            label="创建时间"
            sortable="custom"
            width="160">
          </el-table-column>
          <el-table-column
            prop="labels"
            min-width="200"
            label="标记">
            <template slot-scope="scope">
              <Comp-tags :label="scope.row.labels"></Comp-tags>
            </template>
          </el-table-column>
          <el-table-column
            v-if="buttonAuthority.lead && (buttonAuthority.lead.edit || buttonAuthority.lead.label)"
            label="操作"
            align="center"
            fixed="right"
            width="110">
            <template slot-scope="scope">
              <el-dropdown
                @command="(type)=>{rolDataActive(type,scope.row)}"
                trigger="click"
              >
                <el-button
                  type="text"
                  icon="el-icon-arrow-down"
                  size="small">
                  更多操作
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="edit" v-if="buttonAuthority.lead && buttonAuthority.lead.edit">编辑</el-dropdown-item>
                  <el-dropdown-item command="mark" v-if="buttonAuthority.lead && buttonAuthority.lead.label">标记</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="m-pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes=pagination.pageSizeList
          :current-page=pagination.pageNo
          :page-size=pagination.pageSize
          layout="total, sizes, prev, pager, next"
          :total=pagination.total>
        </el-pagination>
      </div>
    </div>
    <el-dialog title="上传LEAD" :visible.sync="uploadDatas.show" width="400px" class="m-dialog"
               :close-on-click-modal="false" :close-on-press-escape="false" @close="closeUploadDialog">
      <el-form :model="uploadDatas.form" :rules="uploadDatas.rules" ref="refUploadDatas">
        <el-form-item prop="fileName">
          <el-row class="uploadfilerow">
            <el-col class="title" :span="5">上传文件</el-col>
            <el-col :span="13">
              <el-input :disabled="true" v-model="uploadDatas.form.fileName" placeholder="未选择文件"></el-input>
            </el-col>
            <el-col :span="6" class="down">
              <el-upload
                :multiple="false"
                accept=""
                action="/"
                :on-change="handleUpladFileSuccess"
                :show-file-list="false"
                :auto-upload="false">
                <el-button type="text" class="link-btn">文档上传</el-button>
              </el-upload>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row class="uploadfilerow">
            <el-col class="title" :span="5">下载模板</el-col>
            <el-col :span="13">
              <el-input value="下载模板" :disabled="true"></el-input>
            </el-col>
            <el-col :span="6" class="down">
              <el-button type="text" class="link-btn"><a href="/static/xlsTMP/Upload_Leads.xlsx">点击下载</a></el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div class="dialog-tipWords">
        <div class="tipTitle">提示：</div>
        <div class="tipContent">
          1. 不填写的栏位表示不更新<br>
          2. 单次批量上传上限为1000条
        </div>
      </div>
      <div slot="footer">
        <el-button @click="uploadDatas.show = false">取消</el-button>
        <el-button type="primary" @click="uploadDatasSubmit">提交</el-button>
      </div>
    </el-dialog>
    <Comp-Upload-Dialog :show.sync="showUploadDialog" :step.sync="showUploadDialogStep"></Comp-Upload-Dialog>
    <Comp-Mark @submit="markRowData" :show.sync="showMarkDialog" :markData="{type:'2',labelsStr:activeRow.labels}"></Comp-Mark>
    <Comp-Add-Lead @addSuccess="search" :show.sync="showAddLeadData"></Comp-Add-Lead>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import CompUploadDialog from '@/components/CompUploadDialog.vue'
  import CompAddLead from '@/components/CompAddLead.vue'
  import * as LeadsAPI from '@/Api/lead';
  import * as LabelAPI from '@/Api/label'
  import * as FocusAPI from '@/Api/focus'
  import * as UserAPI from '@/Api/user'
  import * as Utils from '@/utils'
  import qs from 'qs'
  export default {
    name: 'LeadsList',
    data () {
      return {
        activeRow: {},
        showMarkDialog: false,
        showAddLeadData:false,
        markabels: [],
        userList: [],
        searchForm: {
          typeinputFH: 'phone',
          inputFH: '',
          typetimeFH: 'create',
          timeFH: Utils.thisWeek(),
          projects: [],
          hstatus: [],
          labels: [],
          astatus: '',
          createUser: '',
          assigner: '',
          isFocus:'false',
          isAssignerFocus:''
        },
        copySearchForm: null,
        showUploadDialog:false,//显示上传进度弹窗
        showUploadDialogStep:'ing',//显示上传进度弹窗 -进度
        showMoreSearchChoise: false,
        pagination: Utils.commonPagination(),
        dataList: [],
        dataListLoading:false,
        pickerOptions: Utils.pickerOptions(),
        uploadDatas: {
          show: false,
          form: {
            fileName: '',
            file: null,
          },
          rules: {
            fileName: [
              {required: true, trigger: 'blur', message: '请上传LEAD文件'}
            ]
          }
        },
        sortInfo: {},
        ajaxSearchParams:{},
      }
    },
    computed: {
      downLoadHref(){
        return LeadsAPI.leadDownload() + '?' + qs.stringify(Object.assign(this.createListParams(), {track: Utils.randomTrack(),token:this.$store.state.app.userInfo.token}), {allowDots: true})
      },
      ...mapGetters([
        'buttonAuthority',
      ]),
    },
    watch:{
      'searchForm.inputFH'(val){
        if(val) {
          this.searchForm.timeFH = null;
        } else {
          this.searchForm.timeFH = Utils.thisWeek();
        }
      },
      '$route'(to) {
        if (to.name == 'LeadsList' && to.query.t) {
          this.showMoreSearchChoise = false;
          this.sortInfo = {}
          this.markabels = []
          this.userList = []
          this.dataList = [];
          this.$refs.dataList.clearSort();
          this.$refs.dataList.clearFilter();
          this.searchForm = Object.assign({}, this.copySearchForm);
          this.pagination = Utils.commonPagination();
          this.search();
        }
      },
    },
    components: {
      CompUploadDialog,
      CompAddLead,
    },
    methods: {
      tableRenderHeader(h, {column}) {
        return h('i', {
          class: ['el-icon-star-off', 'el-icon-star-off-header']
        });
      },
      reset() {
        this.searchForm = Object.assign({}, this.copySearchForm);
      },
      tableSortBy(data) {
        if (!data.order) {
          return;
        }
        this.sortInfo.orderParam = data.prop;
        this.sortInfo.orderType = data.order.substr(0, data.order.length - 6);
        if (this.pagination.pageNo == 1) {
          this.queryList();
        } else {
          this.pagination.pageNo = 1;
        }
      },
     /* tableFilter(data) {
        if(data.focus.length == 1) {
          this.searchForm.isFocus = data.focus[0]
        } else  {
          this.searchForm.isFocus = '';
        }
        this.search();

      },*/
      rolDataActive(type, row) {
        this.activeRow = row;
        if (type == 'edit') {
          this.$router.push({name: 'LeadDetailsLeade', params: {id: row.id + '_' + row.phone}, query: {type: 'edit'}})
        }
        if (type == 'mark') {
          this.showMarkDialog = true;
        }
      },
      markRowData(data){
        LeadsAPI.leadLabel(Object.assign({
          id: this.activeRow.id
        }, data.mark))
          .then(res => {
            if (res.code != 0) {
              this.$notify.warning({
                title: '温馨提示',
                message: res.msg
              })
              return;
            }
            this.queryList();
            this.showMarkDialog = false;
            this.$message({
              message: '标记成功',
              type: 'success'
            });
          })
          .catch(error => {
            console.log(error)
          })

      },
      remoteMarkMethod(queryStr) {
        if (queryStr != '') {
          LabelAPI.labelName({
            type: '2',
            input: queryStr
          })
            .then(res => {
              if (res.code != 0) {
                this.$notify({
                  title: '温馨提示',
                  message: res.msg,
                  type: 'warning'
                })
                return;
              }
              this.markabels = res.data;
            })
            .catch(error => {
              console.log(error);
            })
        }
      },
      remoteUserMethod(queryStr) {
        if (queryStr != '') {
          UserAPI.userNickname({
            input: queryStr
          })
            .then(res => {
              if (res.code != '0') {
                this.$notify({
                  title: '温馨提示',
                  message: res.msg,
                  type: 'warn'
                })
                return;
              }
              this.userList = res.data;
            })
            .catch(error => {
              console.log(error)
            })
        }

      },
      uploadDatasSubmit() {
        this.$refs.refUploadDatas.validate(flg => {
          if (!flg) {
            return;
          }
          this.showUploadDialog = true;
          this.showUploadDialogStep = 'ing';
          let tabHeader = ['phone', 'otherPhone', 'assigner', 'title', 'realName', 'birthday', 'email', 'qq', 'wechat', 'source', 'degree', 'ever','exp', 'root', 'rootTime'];
          Utils.xlsxToJson(this.uploadDatas.form.file, tabHeader)
            .then(res => {
              if(res.length > 1000) {
                this.showUploadDialog = false;
                this.$alert('上传数据不能超过一千条', '温馨提示', {
                  confirmButtonText: '确定',
                  callback: action => {
                    this.$message({
                      type: 'warning',
                      message: `action: ${ action }`
                    });
                  }
                });
                return;
              }
              this.upLoadDatesService(res)
                .then(res => {
                  this.$notify({
                    title: '温馨提示',
                    message: '数据上传成功',
                    type: 'success'
                  })
                  this.showUploadDialogStep = 'success';
                  if (this.pagination.pageNo == 1) {
                    this.queryList();
                  } else {
                    this.pagination.pageNo = 1;
                  }
                  this.uploadDatas.show = false;
                })
                .catch(error => {
                  if (error) {
                    this.showUploadDialogStep = 'exception';
                  } else {
                    this.showUploadDialog = false;
                  }
                })
            })
            .catch(error => {
              this.showUploadDialog = false;
              this.$message({
                message: error,
                type: 'warning'
              });
            })
        })
      },
      upLoadDatesService(array){
        return new Promise((resolve, reject) => {
          LeadsAPI.leadsUpload({
            type: this.uploadDatas.form.type,
            data: JSON.stringify(array)
          })
            .then(res => {
              if (res.code != 0) {
                this.$notify({
                  type: 'warning',
                  title: '温馨提示',
                  message: res.msg,
                })
                reject(true);
                return;
              }
              let _tabHeader = {
                'phone': "手机号码必填",
                'otherPhone': "其他手机号码选填",
                'assigner': "分配给(选填)填写用户号码",
                'title': "称谓选填",
                'realName': "姓名选填",
                'birthday': "出生日期（选填）YYYY-MM-DD",
                'email': "电邮地址选填",
                'qq': "QQ选填",
                'wechat': "WeChat选填",
                'source': "渠道来源选填",
                'degree': "意向度选填",
                'exp': "投资经验选填",
                'ever': "曾接触的投资产品选填",
                'root': "CS获取LEAD途径选填",
                'rootTime': "CS获取LEAD时间（选填）YYYY-MM-DD HH:MM",
                'remark': '错误描述'
              };
              Utils.JsonToXlsx(res.data, _tabHeader)
                .catch(error => {
                  this.$notify({
                    type: 'warning',
                    title: '温馨提示',
                    message: error,
                  })
                })
              resolve();
            })
            .catch(error => {
              console.log(error)
              reject(false);
            })
        })
      },
      activeFocus(data) {
        FocusAPI[data.focus == '1' ? 'toFocus' : 'unFocus']({
          id: data.id,
          type: '2'
        })
          .then(res => {
            if (res.code != 0) {
              this.$notify.warning({
                title: '温馨提示',
                message: res.msg
              })
              return;
            }
            this.$message({
              message: data.focus == '1' ? '关注成功' : '取消关注成功',
              type: 'success'
            });
            if (data.focus == '1') {
              data.focus = '2';
            } else if (data.focus == '2') {
              data.focus = '1';
            }
          })
          .catch(error => {
            console.log(error)
          })
      },
      handleUpladFileSuccess(file){
        this.uploadDatas.form.file = file;
        this.uploadDatas.form.fileName = file.raw.name
      },
      closeUploadDialog(){
        this.uploadDatas.form.file = null;
        this.uploadDatas.form.fileName = '';
      },
      handleSizeChange(size) {
        this.pagination.pageSize = size;
        if (this.pagination.pageNo == 1) {
          this.queryList();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      handleCurrentChange(index) {
        this.pagination.pageNo = index;
        this.queryList();

      },
      search() {
        this.ajaxSearchParams = Utils.searchParamsFormat(this.searchForm);
        if (this.pagination.pageNo == 1) {
          this.queryList();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      createListParams() {
        return Object.assign(this.ajaxSearchParams, {
          pageNo: this.pagination.pageNo,
          pageSize: this.pagination.pageSize
        }, this.sortInfo)
      },
      queryList() {
        this.dataListLoading = true;
        if (this.$refs.dataList) {
          this.$refs.dataList.bodyWrapper.scrollTop = 0;
        }
        LeadsAPI.leadQuery(this.createListParams())
          .then(res => {
            this.dataListLoading = false;
            if (res.code != 0) {
              this.$notify.warning({
                title: '温馨提示',
                message: res.msg
              })
              return;
            }
            this.dataList = res.data.data;
            this.pagination.total = res.data.total;
          })
          .catch(error => {
            this.dataListLoading = false;
            console.log(error)
          })
      },
    },
    created(){
      this.copySearchForm = Object.assign({}, this.searchForm);
      this.search();
    }
  }
</script>

<style scoped lang="scss">
  @import "../../scss/variables";
</style>
